import React, { useCallback, useRef } from "react";
import PickerPanel from "../components/picker-panel";
import Picker from "../components/picker-view";
import useOverlay from "./useOverlay";
import { useCountyDataContext } from "../uses/useCoutryDataContext";
import { CityPickerHookProps } from '../../types/uses/useCityPicker'


const useCityPicker = <T extends {}>() => {
  const { countyData } = useCountyDataContext();
  const overlay = useOverlay();
  const pickerValueRef = useRef([] as any);
  const show = useCallback((props: CityPickerHookProps<T>) => {
    return overlay.show(() => {
      return (
        <PickerPanel
          {...props}
          title={props.title}
          onCancel={() => {
            overlay.close();
            pickerValueRef.current = null
          }}
          onConfirm={() => {
            overlay.close();
            props.onConfirm && props.onConfirm(pickerValueRef.current);
            pickerValueRef.current = null
          }}
        >
          <Picker {...props}
            linkage={true}
            dataSource={countyData}
            onChange={(value) => {
              pickerValueRef.current = [...value];
              props?.onChange?.(value)
            }} />
        </PickerPanel>
      )
    }, {
      type: 'slid-up'
    })
  }, [countyData])
  return { ...overlay, show }
};

export default useCityPicker
